package top.kaoshanji.ch02;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.ch02.textFile.Employee;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Scanner;

/**
 * 代码清单 ch02-01：以文本格式存储对象(2.1.7节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/6 11:19
 */
public class TextFileTest {

    private static final Logger logger = LogManager.getLogger(TextFileTest.class);

    static final String EMPLOYEE_FILE_NAME = "ch02-01-employee.dat";

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 ch02-01：以文本格式存储对象(2.1.7节)...");

        var staff = new Employee[3];

        staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
        staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
        staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

        // 写入
        try (var out = new PrintWriter(EMPLOYEE_FILE_NAME, StandardCharsets.UTF_8)){
            writeData(staff, out);
        }

        // 读取
        try (var in = new Scanner(new FileInputStream(EMPLOYEE_FILE_NAME), StandardCharsets.UTF_8)){
            Employee[] newStaff = readData(in);

            for (Employee e: newStaff) {
                System.out.println(e);
            }

        }

    }

    /**
     * 将 Employee数组数据 写入文件
     * @param employees Employee
     * @param out PrintWriter
     */
    public static void writeData(Employee[] employees, PrintWriter out) {

        out.println(employees.length);

        for (Employee e: employees) {
            writeEmployee(out, e);
        }

    }

    /**
     * 从文件中读取 Employee数组数据
     * @param in Scanner
     * @return Employee
     */
    public static Employee[] readData(Scanner in) {

        int n = in.nextInt();
        in.nextLine();

        var employees = new Employee[n];
        for (int i = 0; i < n; i++) {
            employees[i] = readEmployee(in);
        }
        return employees;

    }


    /***
     * 写入一个 Employee
     * @param out PrintWriter
     * @param e Employee
     */
    public static void writeEmployee(PrintWriter out, Employee e) {

        out.println(e.getName() + "|" + e.getSalary() + "|" + e.getHireDay());

    }

    /**
     * 从缓存数据中读取一个 Employee
     * @param in Scanner
     * @return Employee
     */
    public static Employee readEmployee(Scanner in) {

        String line = in.nextLine();
        String[] tokens = line.split("\\|");
        String name = tokens[0];
        double salary = Double.parseDouble(tokens[1]);
        LocalDate hireDate = LocalDate.parse(tokens[2]);
        int year = hireDate.getYear();
        int month = hireDate.getMonthValue();
        int day = hireDate.getDayOfMonth();
        return new Employee(name, salary, year, month, day);

    }


}
